cc.Class({
    extends: cc.Component,

    properties: {
        dataEventHandler:null,
        roomId:null,
        maxNumOfGames:0,
        numOfGames:0,
        numOfMJ:0,
        seatIndex:-1,
        seats:null,
        turn:-1,
        gangNum:0,
        button:-1,
        shaizival:null,
        dingque:-1,
        chupai:-1,
        paiDuPos:null,
        isDingQueing:false,
        isHuanSanZhang:false,
        isDingOrMaiDi:false,//是否顶底or买底中,现在是没有用到的，
        maidiIng:false,
        dingDiOrMaiDi:-1,//是否顶底or买底
        isZhuang:false,//是否为庄
        caishu:-1,
        dizhu:0,
        dishu:null,
        gamestate:"",
        isOver:false,
        youXianPai:null,//是一个数组
        // chiOpsArr:[],
        gangPengChiSeats:[],
        // paiOfHGPC:-1,//要胡/杠/碰/吃的牌
        isGameSync:false,//是否是断线重连进来的。
        isGameBegin:false,//主要用于判断，可能会出现game_begin_push 会出现在game_finished之前。会出现的bug.
        maiOrDingDiArr:[],//默认5为不买
        gameMaiOrDing:-1,//用于MJGame.js中，确定是买底还是顶底。
        isInitZhuang:false,
        isshaizi:null,
        difen:0,
        ismaidi:false,
        // chu_pai_animation_data:null,//主要用于判断,是否还留在folds中
        // foo: {
        //    default: null,
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
    },

    resetMaiOrDingArr:function(){
        this.maiOrDingDiArr=[5,5,5,5]; 
        if(cc.vv.setPeople.isERMJ()){
            this.maiOrDingDiArr=[5,5];
        }
    },
    
    reset:function(){
        console.log("reset of GameNetMgr.js");
        this.turn = -1;
        this.chupai = -1,
        this.dingque = 3;
        this.button = -1;
        this.gangNum = 0;
        this.gamestate = "";
        this.dingque = -1;
        this.isDingQueing = false;
        this.isHuanSanZhang = false;
        this.isInitZhuang = false;
        this.isDingOrMaiDi=false;
        this.dingDiOrMaiDi=-1;
        this.isZhuang=false;
        this.caishu=-1;
        this.dizhu=0;
        
        this.curaction = null;
        for(var i = 0; i < this.seats.length; ++i){
            this.seats[i].holds = [];
            this.seats[i].folds = [];
            this.seats[i].pengs = [];
            this.seats[i].chis = [];
            this.seats[i].angangs = [];
            this.seats[i].diangangs = [];
            this.seats[i].wangangs = [];
            this.seats[i].dingque = -1;
            this.seats[i].ready = false;
            this.seats[i].hued = false;
            
        }
        // this.paiOfHGPC=-1;
    },
    
    clear:function(){
        var str=("clear of GameNetMgr.js");
        str+=" game_state="+this.gamestate;
        this.dataEventHandler = null;

        // this.seats = null;
        // this.roomId = null;
        // this.maxNumOfGames = 0;
        // this.numOfGames = 0;
        this.resetMaiOrDingArr();
        // this.paiOfHGPC=-1;
        this.isGameSync=false;
        this.isGameBegin=false;
        this.gameMaiOrDing=-1;
        this.isInitZhuang=false;

        // for(var i=0;i<4;i++)
        // {
        //     var seat={};
        //     seat.gang=[];
        //     seat.peng=[];
        //     seat.chis=[];
        //     this.gangPengChiSeats.push(seat);
        // }

        if(this.isOver == null){
            this.seats = null;
            this.roomId = null;
            this.maxNumOfGames = 0;
            this.numOfGames = 0;
            var lengt=4;
            if(cc.vv.setPeople.isERMJ()){
                lengt=2;
            }
            for(var i=0;i<lengt;i++)
            {
                var seat={};
                seat.gang=[];
                seat.peng=[];
                seat.chis=[];
                this.gangPengChiSeats.push(seat);
            }   
        }
    },
    
    dispatchEvent(event,data){
        if(this.dataEventHandler){
            this.dataEventHandler.emit(event,data);
        }    
    },
    
    getSeatIndexByID:function(userId){

        if(this.seats)
        {
            for(var i = 0; i < this.seats.length; ++i){
                var s = this.seats[i];
                if(s.userid == userId){
                    return i;
                }
            }
        }else{
            console.log("seat is null of getSeatIndexByID");
        }
        return -1;
    },
    
    isOwner:function(){
        return this.seatIndex == 0;   
    },
    
    getSeatByID:function(userId){
        var seatIndex = this.getSeatIndexByID(userId);
        console.log("seatIndex of getSeatByID"+seatIndex);
        if(seatIndex<0){
            return null;
        }
        var seat = this.seats[seatIndex];
        return seat;
    },
    
    getSelfData:function(){
        return this.seats[this.seatIndex];
    },
    
    getLocalIndex:function(index){

        var ret = (index - this.seatIndex + 4) % 4;

        if(cc.vv.setPeople.isERMJ()){
            ret = (index - this.seatIndex + 2) % 2;
        }
        return ret;
    },
    
    prepareReplay:function(roomInfo,detailOfGame){
        this.roomId = roomInfo.id;
        this.seats = roomInfo.seats;
        this.turn = detailOfGame.base_info.button;
        var baseInfo = detailOfGame.base_info;
        for(var i = 0; i < this.seats.length; ++i){
            var s = this.seats[i];
            s.seatindex = i;
            s.score = null;
            s.holds = baseInfo.game_seats[i];
            s.pengs = [];
            s.chis=[];
            s.angangs = [];
            s.diangangs = [];
            s.wangangs = [];
            s.folds = [];
            s.online=false;
            console.log(s);
            if(cc.vv.userMgr.userId == s.userid){
                this.seatIndex = i;
            }
        }
        // this.paiOfHGPC=-1;
        cc.log("baseInfo.type="+baseInfo.type);
        this.conf = {
            type:baseInfo.type,
        }
        if(this.conf.type == null){
            this.conf.type == "wzsr";
            this.resetMaiOrDingArr();
        }
    },
    
    getWanfa:function(){
        var conf = this.conf;
        if(conf && conf.maxGames!=null && conf.maxFan!=null){
            var strArr = [];
            strArr.push(conf.maxGames + "局");
            strArr.push(conf.maxFan + "番封顶");
            if(conf.hsz){
                strArr.push("换三张");   
            }
            if(conf.zimo == 1){
                strArr.push("自摸加番");
            }
            else{
                strArr.push("自摸加底");
            }
            if(conf.jiangdui){
                strArr.push("将对");   
            }
            if(conf.dianganghua == 1){
                strArr.push("点杠花(自摸)");   
            }
            else{
                strArr.push("点杠花(放炮)");
            }
            if(conf.menqing){
                strArr.push("门清、中张");   
            }
            if(conf.tiandihu){
                strArr.push("天地胡");   
            }
            return strArr.join(" ");
        }
        return "";
    },
    
    initHandlers:function(){
        var self = this;
        cc.vv.net.addHandler("login_result",function(data){
            console.log(data);
            if(data.errcode === 0){
                var data = data.data;
                self.roomId = data.roomid;
                self.conf = data.conf;

                self.resetMaiOrDingArr();
                self.maxNumOfGames = data.conf.maxGames;
                self.dishu = data.conf.dishu;
                self.ismaidi = data.conf.isNeedOperDi == 1;
                self.numOfGames = data.numofgames;
                self.seats = data.seats;
                self.seatIndex = self.getSeatIndexByID(cc.vv.userMgr.userId);
                console.log("myself holds="+self.seats[self.seatIndex].holds);
                self.isOver = false;
                self.difen =data.conf.difen;
            }
            else{
                cc.director.loadScene("login");
                console.log(data.errmsg);   
            }
            cc.log("login_result","data.conf.type="+self.conf.type);
        });
    
        cc.vv.net.addHandler('reconnect_prepare_push',function(data) {
            console.log('reconnect_prepare_push');
            console.log(data);
            self.roomId = data.roomid;
            self.conf = data.conf;
            self.maxNumOfGames = data.conf.maxGames;
            self.dishu = data.conf.dishu;
            self.ismaidi = data.conf.isNeedOperDi == 1;
            self.difen =data.conf.difen;

            self.numOfGames = data.numofgames;
            self.seats = data.seats;
            self.seatIndex = self.getSeatIndexByID(cc.vv.userMgr.userId);

            self.dispatchEvent("refresh_sync_ready_infs");
        });
                
        cc.vv.net.addHandler("login_finished",function(data){
            console.log("login_finished+self.conf.type"+self.conf.type);
            //重置

            // self.conf.type
            console.log("---------------- login_finished ___cc.vv.isFourMen="+cc.vv.isFourMen+"isERMJ="+cc.vv.setPeople.isERMJ());

            if(!cc.vv.setPeople.isERMJ()&&cc.vv.isFourMen){
                console.log("-------------is four men reEnter =================");
                // return;
            }else{
                console.log("============ enter mjgame ==================");
                cc.director.loadScene("mjgame");
            }
            // cc.director.loadScene("mjgame");
        });

        cc.vv.net.addHandler("exit_result",function(data){
            console.log("exit_result "+data);

            self.roomId = null;
            self.turn = -1;
            self.dingque = -1;
            self.isDingQueing = false;
            self.isDingOrMaiDi=false;
            self.seats = null;
            
            self.isDingOrMaiDi=false;
            self.dingDiOrMaiDi=-1;
            self.isZhuang=false;
            self.caishu=-1;
            self.dizhu=0;
        });
        
        cc.vv.net.addHandler("exit_notify_push",function(data){
           console.log("exit_notify_push "+data);
           var userId = data;
           var s = self.getSeatByID(userId);
           if(s != null){
               s.userid = 0;
               s.name = "";
               self.dispatchEvent("user_state_changed",s);
               console.log("退出房间，刷新");
               self.dispatchEvent("user_state_changedicon",s);
           }
        });
        
        cc.vv.net.addHandler("dispress_push",function(data){
            console.log("dispress_push "+data);
            self.roomId = null;
            self.turn = -1;
            self.dingque = -1;
            self.isDingQueing = false;
            self.isDingOrMaiDi=false;
            self.seats = null;
            
            self.isDingOrMaiDi=false;
            self.dingDiOrMaiDi=-1;
            self.isZhuang=false;
            self.caishu=-1;
            self.dizhu=0;
        });
                
        cc.vv.net.addHandler("disconnect",function(data){
            var str=("addHandler disconnect of GameNetMgr.js"+data);

            cc.vv.net_isConnect=false;
            console.log("cc.vv.net_isConnect="+cc.vv.net_isConnect);
            if(self.roomId == null){
                str+=" self.roomId";
                cc.director.loadScene("hall");
            }
            else{
                if(self.isOver == false){
                    cc.vv.userMgr.oldRoomId = self.roomId;
                    str+=" dispatchEvent('disconnect')";
                    self.dispatchEvent("disconnect");                    
                }
                else{
                    str+=" self.roomId = null;";
                    self.roomId = null;
                }
            }
            console.log(str);
        });
        
        cc.vv.net.addHandler("new_user_comes_push",function(data){
            console.log("new_user_comes_push");
            console.log(data);
            var seatIndex = data.seatindex;
            if(self.seats[seatIndex].userid > 0){
                self.seats[seatIndex].online = true;
            }
            else{
                data.online = true;
                self.seats[seatIndex] = data;
            }
            self.dispatchEvent('new_user',self.seats[seatIndex]);
        });
        
        cc.vv.net.addHandler("user_state_push",function(data){
            console.log("user_state_push");
            console.log(data.userid);
            var userId = data.userid;
            var seat = self.getSeatByID(userId);
            if(seat)
            {
                seat.online = data.online;
                self.dispatchEvent('user_state_changed',seat);
            }else
            {
                console.log("seat is null or undefined");
            }
            
        });
        
        cc.vv.net.addHandler("user_ready_push",function(data){
            console.log("user_ready_push of id= "+data.userid+" ready="+data.ready);
            var userId = data.userid;
            var seat = self.getSeatByID(userId);
            seat.ready = data.ready;
            self.dispatchEvent('user_state_changed',seat);
        });
        
        cc.vv.net.addHandler("game_holds_push",function(data){
            console.log("game_holds_push");
            var seat = self.seats[self.seatIndex]; 
            console.log(data);
            seat.holds = data;
            
            for(var i = 0; i < self.seats.length; ++i){
                var s = self.seats[i]; 
                if(s.folds == null){
                    s.folds = [];
                }
                if(s.pengs == null){
                    s.pengs = [];
                }
                if(s.chis==null)
                {
                    s.chis=[];
                }
                if(s.angangs == null){
                    s.angangs = [];
                }
                if(s.diangangs == null){
                    s.diangangs = [];
                }
                if(s.wangangs == null){
                    s.wangangs = [];
                }
                s.ready = false;
            }
            self.dispatchEvent('game_holds');
        });
         
        cc.vv.net.addHandler("game_begin_push",function(data){
            console.log('game_begin_push');
            console.log(data);
            self.button = data.banker;
            self.turn = self.button;
            // self.gamestate = "playing";
            // self.chupai = 1;
	        self.isGameBegin=true;
            self.isDingOrMaiDi = false;
            self.maiOrDingDiArr=data.maiOrDingDi;
            // self.chu_pai_animation_data=null;
            // self.dizhu = data      //底数 
            self.dispatchEvent('game_begin');
            console.log("initZhuang of game_begin");
            self.dispatchEvent('initZhuang',self.button);
        });

        cc.vv.net.addHandler('reconnect_ok_push',function(data) {
            console.log('reconnect_ok_push');
            console.log(data);
            self.conf = data.conf;//取得配置
            self.maxNumOfGames = data.conf.maxGames;//4局还是8局
            self.dishu = data.conf.dishu;//底数
            self.ismaidi = data.conf.isNeedOperDi == 1;
            self.numOfGames = data.numofgames;//进行到第几局
            self.difen =data.conf.difen;//底分
            self.roomId=data.roomid;//

            self.gamestate = data.state;//游戏状态
            self.numOfMJ = data.numofmj;//剩下麻将数
            self.button = data.button;//庄
            self.turn = data.turn;//出牌者
            self.chupai = data.chuPai;//出那张牌。
            self.caishu=data.caishen;//财神


            for(var i=0;i<data.seats.length;i++) {
                var sd=data.seats[i]
                console.log(sd);
                self.seats[i]=sd;
                if(sd.maiOrDingDi) {
                    console.log('maiOrDingDi='+sd.maiOrDingDi);
                    self.maiOrDingDiArr[i]=sd.maiOrDingDi;  
                }else {
                    console.log('maiOrDingDi is null');
                    self.maiOrDingDiArr[i]=5;
                }  
            }

            console.log('cc.vv.userMgr.userId='+cc.vv.userMgr.userId);
            self.seatIndex = self.getSeatIndexByID(cc.vv.userMgr.userId);
            console.log('self.seatIndex='+self.seatIndex);
            //本家优先牌
            self.youXianPai=data.seats[self.seatIndex].youxian;
            self.dispatchEvent('refresh_sync_infs');
        });

        //断线重连
        cc.vv.net.addHandler("game_sync_push",function(data){
            console.log("game_sync_push");
            console.log(data);

            //用于手动刷新处理
            if(!cc.vv.setPeople.isERMJ()&&cc.vv.isFourMen){
               cc.vv.ifFourMen=false;
               cc.director.loadScene("mjgame");
            }

            self.isGameSync=true;
            //不应该把chu_pai_animation_data设置为null
            // self.chu_pai_animation_data=null;

            console.log("self.isGameSync"+self.isGameSync);
            self.numOfMJ = data.numofmj;
            self.paiDuPos = data.paidun;
            self.gamestate = data.state;
            console.log("gamestate="+self.gamestate);

            if(self.gamestate == "dingque"){
                self.isDingQueing = true;
                //gamestate=="dingque"要换成""dingOrmai"
                self.isDingOrmai=true;
            }
            else if(self.gamestate == "huanpai"){
                self.isHuanSanZhang = true;
            }

            self.isDingOrMaiDi=false;
            self.dingDiOrMaiDi=-1;
            self.isZhuang=false;
            
            self.dizhu=0;
            
            self.turn = data.turn;
            self.button = data.button;
            self.chupai = data.chuPai;
            self.caishu=data.caishen;//新添加的内容

            //显示庄家
            self.isInitZhuang=true; 
            cc.log("initZhuang","gameNetMgr");

            for(var i = 0; i < self.seats.length; ++i){
                // console.log("i="+i);
                var seat = self.seats[i];
                var sd = data.seats[i];
                seat.holds = sd.holds;
                seat.folds = sd.folds;
                seat.angangs = sd.angangs;
                seat.diangangs = sd.diangangs;
                seat.wangangs = sd.wangangs;
                self.gangNum += (seat.angangs.length + seat.wangangs.length + seat.diangangs.length);
                seat.pengs = sd.pengs;
                seat.chis=sd.chis;//添加的吃。
                
                // seat.dingque = sd.que;
                seat.hued = sd.hued; 
                seat.iszimo = sd.iszimo;
                seat.huinfo = sd.huinfo;

                //新加__同步买底还是顶底。
                self.maiOrDingDiArr[i]=sd.maiOrDingDi;
                console.log("maiOrDingDiArr["+i+"]="+sd.maiOrDingDi);
                //确定本家的优先牌。
                if(i == self.seatIndex){
                    console.log("self.seatIndex"+self.seatIndex);
                    self.dingque = sd.que;
                    self.youXianPai=null;
                    self.youXianPai=sd.youxian;//新添加的内容。
                    console.log("data.youxian"+sd.youxian);
                }
           }
           var type=self.maiOrDingDiArr[self.seatIndex];
           console.log("maiOrDingDiArr[self.seatIndex]="+self.maiOrDingDiArr[self.seatIndex]);
           cc.vv.isFourMen=false;
           console.log("cc.vv.isFourMen="+cc.vv.isFourMen);

           self.dispatchEvent('initZhuang',data.button);
           if(type==1||type==3){
               //感觉有bug,还没有细看。
               self.gameMaiOrDing=data;
               return;
           }
        //    self.aaSync=true;

        });
        
        cc.vv.net.addHandler("game_dingque_push",function(data){
            console.log("game_dingque_push "+data);
            self.isDingQueing = true;
            self.isHuanSanZhang = false;
            self.dispatchEvent('game_dingque');
            self.isDingOrMaiDi=true;
            //self.dispatchEvent('game_dingOrmai')
        });

        cc.vv.net.addHandler("is_mai_or_ding_di",function(data){//开始买底
            var str="is_mai_or_ding_di "+data.maiOrDingDi;
            self.button = data.banker;
            self.maidiIng = true;
            //1为选择买底，3为选择顶底。
            data = data.maiOrDingDi;
            self.gameMaiOrDing=data;
            self.maiOrDingDiArr[self.seatIndex]=data;
            if(1==data||3==data)
            {
                str+=" send is_mai_or_ding_di to other node"
                self.dispatchEvent('is_mai_or_ding_di',data);
            }
            self.dispatchEvent('initpaiqiang',self.button);
            cc.log("initZhuang","is_mai_or_ding_di");
            self.dispatchEvent('initZhuang',self.button);
            console.log(str);
        });

        cc.vv.net.addHandler("buy_and_double_base",function(data){//买底顶底结束
            //不买为5 2为买底，4为顶底。
            console.log("buy_and_double_base "+data.type +" seatIndex="+data.seatIndex);
            self.maiOrDingDiArr[data.seatIndex]=data.type;
            console.log("self.maiOrDingDiArr[self.seatIndex]="+self.maiOrDingDiArr[data.seatIndex]);
            self.dispatchEvent('buy_and_double_base',data);
            
        });

        cc.vv.net.addHandler("game_huanpai_push",function(data){
            console.log("game_huanpai_push "+data);
            self.isHuanSanZhang = true;
            self.dispatchEvent('game_huanpai');
        });
        
        cc.vv.net.addHandler("hangang_notify_push",function(data){
            console.log("hangang_notify_push "+data);
            self.dispatchEvent('hangang_notify',data);
        });
        
        cc.vv.net.addHandler("game_action_push",function(data){
            self.curaction = data;
            console.log("game_action_push");
            console.log(data);
            // if(data)
            // {
            //     self.paiOfHGPC=data.pai;
            // }
            // console.log("self.paiOfHGPC="+self.paiOfHGPC);
            // if(data==null){
            // }
            self.dispatchEvent('game_action',data);
            if(data==null){
                console.log("data is null");
                return;
            }
            var str="data.hu="+data.hu+" data.gang="+data.gang+" data.peng="+data.peng+" data.chi="+data.chi+" data.chipai="+data.chipai;
            console.log("emit data of show_log");
            if(cc.vv.logNodeHandle){
                cc.vv.logNodeHandle.emit('show_log',str);
            }else{
                cc.vv.logNodeHandleArr=[];
                cc.vv.logNodeHandleArr.push(str);
                console.log("logNodeHandle is null");
            }
            // self.dispatchEvent('show_log',str);
        });
        
        cc.vv.net.addHandler("game_chupai_push",function(data){
            console.log('game_chupai_push');
            console.log(data);
            var turnUserID = data;
            var si = self.getSeatIndexByID(turnUserID);
            self.doTurnChange(si);
        });
        
        cc.vv.net.addHandler("game_num_push",function(data){
            console.log("game_num_push "+data);
            self.numOfGames = data;
            self.dispatchEvent('game_num',data);
        });

        cc.vv.net.addHandler("game_over_push",function(data){
            console.log('game_over_push data='+data);
            var results = data.results;
            self.isGameSync = false;
            for(var i = 0; i <  self.seats.length; ++i){
                if(results.length != 0)
                {
                    self.seats[i].score = results[i].totalscore;
                }
                //用于开始新一局后，准备页面。
                self.seats[i].ready=false;
                self.dispatchEvent('user_state_changed',self.seats[i]);    
            }
            self.dispatchEvent('game_over',results);
            if(data.isend){
                self.isOver = true;
                self.dispatchEvent('game_end');    
            }
            self.reset();
        });
        cc.vv.net.addHandler('round_score',function(data)
        {
            cc.log("round_score",data);
            self.dispatchEvent('round_score',data);
        });
        
        cc.vv.net.addHandler("mj_count_push",function(data){
            console.log('mj_count_push');
            self.numOfMJ = data;
            //console.log(data);
            self.dispatchEvent('mj_count',data);
        });
        
        cc.vv.net.addHandler("hu_push",function(data){
            console.log('hu_push');
            console.log(data);
            self.doHu(data);
        });
        
        cc.vv.net.addHandler("game_chupai_notify_push",function(data){
            console.log("game_chupai_notify_push");
            // console.log(data);
            var userId = data.userId;
            var pai = data.pai;
            var si = self.getSeatIndexByID(userId);
            self.doChupai(si,pai,data.holds);
        });
        
        //自己摸牌
        cc.vv.net.addHandler("game_mopai_push",function(data){
            console.log('game_mopai_push:'+data);
            self.doMopai(self.seatIndex,data);
            // self.dispatchEvent('mo_pai',data);
        });
        
        //用于刷新seat.fold的牌。
        cc.vv.net.addHandler("guo_notify_push",function(data){
            console.log('guo_notify_push');
            var userId = data.userId;
            var paiArr = data.folds;
            console.log("paiArr="+paiArr);
            var si = self.getSeatIndexByID(userId);
            // if(self.chu_pai_animation_data){
            //     self.chu_pai_animation_data=null;
            //     pai=null;
            //     return;
            // }
            self.doGuo(si,paiArr);
        });

        //用于刷新seat.fold的牌。
        cc.vv.net.addHandler("chu_pai_animation_push",function(data){
            // cc.log("chu_pai_animation_push",data);
            // self.chu_pai_animation_data=data;
            var userId = data.userId;
            var paiArr = data.folds;
            console.log("paiArr="+paiArr);
            var si = self.getSeatIndexByID(userId);
            self.doGuo(si,paiArr);
        });
        
        cc.vv.net.addHandler("guo_result",function(data){
            console.log('guo_result');
            self.dispatchEvent('guo_result');
        });
        
        cc.vv.net.addHandler("guohu_push",function(data){
            console.log('guohu_push');
            self.dispatchEvent("push_notice",{info:"过胡",time:1.5});
        });
        
        cc.vv.net.addHandler("game_huanpai_result_push",function(data){
            console.log('game_huanpai_result_push');
            var info = "";
            if(data == 0){
                info = "换对家牌";
            }
            else if(data == 1){
                info = "换下家牌";
            }
            else{
                info = "换上家牌";
            }
            self.dispatchEvent("game_huanpai_result");
            self.dispatchEvent("push_notice",{info:info,time:0.8});
        });
        
        cc.vv.net.addHandler("peng_notify_push",function(data){
            console.log('peng_notify_push');
            console.log(data);
            //接收者
            var userId = data.userid;
            var pai = data.pai;
            var si = self.getSeatIndexByID(userId);
            self.doPeng(si,data.pengs,data.holds);
            // if()
            var turn_userid = data.turn_userid;
            console.log("turn user id == "+turn_userid);
            
            //出牌者
            if (turn_userid != null)
            {
                self.doRefreshFolds(turn_userid,data.folds);
            }
            // self.paiOfHGPC=-1;
        });
        
        cc.vv.net.addHandler("gang_notify_push",function(data){
            console.log('gang_notify_push');
            console.log(data);
            var userId = data.userid;
            var pai = data.pai;
            var si = self.getSeatIndexByID(userId);
            //wangangs,angangs,diangangs,pengs,gangtype,holds
            self.doGang(si,data);
            if("diangang"==data.gangtype){
                var turn_userid = data.turn_userid;
                if (turn_userid != null)
                {
                    self.doRefreshFolds(turn_userid,data.folds);
                }
            }
            // self.paiOfHGPC=-1;
        });
        
        cc.vv.net.addHandler("game_dingque_notify_push",function(data){
            console.log("game_dingque_notify_push "+data);
            self.dispatchEvent('game_dingque_notify',data);
        });
        
        cc.vv.net.addHandler("game_dingque_finish_push",function(data){
            console.log("game_dingque_finish_push "+data);

            for(var i = 0; i < data.length; ++i){
                self.seats[i].dingque = data[i];
            }
            self.dispatchEvent('game_dingque_finish',data);
        });
        
        
        cc.vv.net.addHandler("chat_push",function(data){
            console.log("chat_push "+data);
            self.dispatchEvent("chat_push",data);    
        });
        
        cc.vv.net.addHandler("quick_chat_push",function(data){
            console.log("quick_chat_push");
            console.log(data);
            self.dispatchEvent("quick_chat_push",data);
        });
        
        cc.vv.net.addHandler("emoji_push",function(data){
            self.dispatchEvent("emoji_push",data);
        });
        
        cc.vv.net.addHandler("dissolve_notice_push",function(data){
            console.log("dissolve_notice_push"); 
            console.log(data);
            self.dispatchEvent("dissolve_notice",data);
        });
        
        cc.vv.net.addHandler("dissolve_cancel_push",function(data){
            console.log("dissolve_cancel_push "+data);
            self.dispatchEvent("dissolve_cancel",data);
        });
        
        cc.vv.net.addHandler("voice_msg_push",function(data){
            self.dispatchEvent("voice_msg",data);
        });
        
        // cc.vv.net.addHandler("game_init_caishen",function(data){
        //     console.log("game_init_caishen");
        //     console.log(data);
        //     self.caishu=data;
        //     console.log("self.caishu"+self.caishu);
        //     // cc.director.loadScene("mjgame");
        //     self.dispatchEvent('init_caishen',data);
        // });
        
        cc.vv.net.addHandler("game_youxian_push",function(data){
            console.log("game_youxian_push");
            console.log(data);
            //先置空，再赋值.
            self.youXianPai=null;
            self.youXianPai=data;
            console.log("youXianPai"+self.youXianPai);
            self.dispatchEvent("youxian_push",data);
        });
        
        cc.vv.net.addHandler("chi_notify_push",function(data){
            console.log("chi_notify_push");
            console.log(data);
            var userId = data.userid;
            // var paiArr = data.chipaiarr;
            var si = self.getSeatIndexByID(userId);
            //刷新手牌跟显示吃碰杠.
            self.doChi(si,data.chis,data.holds);
            // console.log("self.chu_pai_animation_data.userId="+self.chu_pai_animation_data.userId);
            
            var turn_userid = data.turn_userid;
            console.log("turn_userId="+data.turn_userid);
            if (turn_userid != null)
            {
                //刷新出牌者的folds牌。
                self.doRefreshFolds(turn_userid,data.folds);
            }
            
            // self.paiOfHGPC=-1;
        });

        //是其他人摸牌
        cc.vv.net.addHandler("mopai_push",function(data)
        {
            console.log("mopai_push");
            // console.log(data);
            self.dispatchEvent("mopai_push",data);
        });
        //确定庄家
        cc.vv.net.addHandler("banker_push",function(data)
        {

            self.button = data.button;
            self.shaizival = data.point1 + data.point2;
            self.isshaizi = data;
            console.log("banker_push of data="+data);
            console.log(data);
            self.dispatchEvent("banker_push",data);
        });

        //确定牌墙位置
        cc.vv.net.addHandler("paidun_push",function(data)
        {
            console.log("paidun_push of data ="+data);
            console.log(data);
            self.button = data.banker;
            self.caishu = data.caishenPai;
            self.paiDuPos = data.point1+data.point2;
            console.log(self.ismaidi);
            if(!self.ismaidi)
            {
                console.log("initpaiqiang & initZhuang");
                self.dispatchEvent('initpaiqiang',self.button);
                self.dispatchEvent('initZhuang',self.button);
            }
            // self.dispatchEvent('initpaiqiang',self.button);
            self.dispatchEvent("paidun_push",data);
        });
        cc.vv.net.addHandler("wait_other",function(data)
        {
            console.log("wait_other of data="+data);
            self.dispatchEvent("wait_other",data);
        });

        cc.vv.net.addHandler("game_status_push",function(data)
        {
            console.log("game_status_push="+data.state);
            self.gamestate=data.state;
        });

        cc.vv.net.addHandler("error_msg",function(data)
        {
            console.log("error_msg of data="+ data);
            console.log(data.content);
        });

        // console.log("maiOrDingDiArr 重置 of init GameNetMgr...........");
    },
    
    doGuo:function(seatIndex,paiArr){
        var seatData = this.seats[seatIndex];
        // cc.log("folds",folds);
        if(paiArr==null){
            console.log("pai=null ");
            return;
        }
        seatData.folds=paiArr;
        // folds.push(pai);
        this.dispatchEvent('guo_notify',seatData);    
    },

    doRefreshFolds:function(userid,paiArr){
        console.log("do RefreshFolds ");
        var seatIndex=this.getSeatIndexByID(userid);
        console.log("seatIndex="+seatIndex);
        var seatData = this.seats[seatIndex];
        // if()
        if(paiArr==null){
            console.log("pai=null ");
            return;
        }
        seatData.folds=paiArr;
        // folds.push(pai);
        this.dispatchEvent('refresh_folds',seatData);
    },
    
    doMopai:function(seatIndex,data){
        console.log("data.hold="+data.holds);
        var seatData = this.seats[seatIndex];
        if(data.holds){
            seatData.holds=data.holds;
            this.dispatchEvent('game_mopai'/*,{seatIndex:seatIndex,pai:pai}*/);            
        }
    },
    
    doChupai:function(seatIndex,pai,holds){
        console.log("doChupai");
        this.chupai = pai;
        var seatData = this.seats[seatIndex];
        cc.log("seatData.folds",seatData.folds);
        if(holds){         
            seatData.holds=holds;    
            // var idx = seatData.holds.indexOf(pai);
            // seatData.holds.splice(idx,1);
        }

        //可以不用了。
        // if(this.youXianPai)
        // {
        //     if(this.seatIndex==seatIndex)
        //     {
        //         var idx= this.youXianPai.indexOf(pai);
        //         this.youXianPai.splice(idx,1);
        //         console.log("remove youxianpai"+pai+" idx="+idx);
        //     }  
            
        // }
        this.dispatchEvent('game_chupai_notify',{seatData:seatData,pai:pai});    
    },
    
    doPeng:function(seatIndex,pengs,holds){
        var seatData = this.seats[seatIndex];
        if(pengs) {
            seatData.pengs=pengs;
        }

        if(holds) {
            seatData.holds=holds;
        }

        // //移除手牌
        // if(seatData.holds){
        //     for(var i = 0; i < 2; ++i){
        //         var idx = seatData.holds.indexOf(pai);
        //         console.log("doPeng",idx);
        //         if(idx==-1){
        //             console.log("idx is null in seatData.holds");
        //             continue;
        //         }
        //         seatData.holds.splice(idx,1);
        //     }                
        // }
            
        // //更新碰牌数据
        // var pengs = seatData.pengs;
        // pengs.push(pai);
            
        this.dispatchEvent('peng_notify',seatData);
    },
    
    //
    doChi:function(seatIndex,chipaiArr,holds)
    {
        // console.log("-----------------------chipai="+pai);
        var seatData=this.seats[seatIndex];
        console.log(seatData);

        if(holds) {
            console.log("holds="+holds);
            seatData.holds=holds;
        }
        if(chipaiArr) {
            console.log("chipaiArr="+chipaiArr);
            seatData.chis=chipaiArr;
            this.dispatchEvent('chi_notify',seatData);
        }
        
        // if(seatData.holds)
        // {
        //     for(var i=0;i<paiArr.length;i++)
        //     {
        //         if(pai==paiArr[i])
        //         {
        //             console.log("not remove pai"+paiArr[i]);
        //             continue;
        //         }
        //         console.log("seatData.holds of index="+seatData.holds.indexOf(parseInt(paiArr[i])));
        //         var idx=seatData.holds.indexOf(parseInt(paiArr[i]));
        //         if(idx==-1){
        //             console.log("idx is -1,because  ");
        //             continue;
        //         }
        //         seatData.holds.splice(idx,1);
        //     }
        // }
        
        // if(paiArr)
        // {
        //     if(seatData)
        //     {
        //         console.log("doChi"+paiArr.length);
        //         for(var i=0;i<paiArr.length;i++)
        //         {
        //             console.log("paiArr"+i);
        //             seatData.chis.push(paiArr[i]);
        //         }
        //         console.log("seatData.chis"+seatData.chis.length);
        //         this.dispatchEvent('chi_notify',seatData);
        //     }
        // }
            
    },
    
    getGangType:function(seatData,pai){
        if(seatData.pengs.indexOf(pai) != -1){
            return "wangang";
        }
        else{
            var cnt = 0;
            for(var i = 0; i < seatData.holds.length; ++i){
                if(seatData.holds[i] == pai){
                    cnt++;
                }
            }
            if(cnt == 3){
                return "diangang";
            }
            else{
                return "angang";
            }
        }
    },
    setName:function(name,len,isLong)
    {
        var newLength = 0; 
        var newStr = ""; 
        var chineseRegex = /[^\x00-\xff]/g; 
        var singleChar = ""; 
        var strLength = name.replace(chineseRegex,"**").length; 
        for(var i = 0;i < strLength;i++) 
        { 
            singleChar = name.charAt(i).toString(); 
            if(singleChar.match(chineseRegex) != null) 
            { 
                newLength += 2; 
            }     
            else 
            { 
                newLength++; 
            } 
            if(newLength > len) 
            { 
                break; 
            } 
            newStr += singleChar; 
        } 
     
        if(isLong && strLength > len) 
        { 
            newStr += "..."; 
        } 
        return newStr;
    },
    doGang:function(seatIndex,data){
        var seatData = this.seats[seatIndex];
        console.log("dogang");
        console.log(data);
        if(data.holds) {
            seatData.holds=data.holds;
        }

        if(data.wangangs) {
            seatData.wangangs=data.wangangs;
        }

        if(data.peng){
            seatData.pengs=data.pengs;
        }

        if(data.angangs) {
            seatData.angangs=data.angangs;
        }

        if(data.diangangs) {
            seatData.diangangs=data.diangangs;
        }

        // if(!data.gangtype){
        //     gangtype = this.getGangType(seatData,pai);
        // }
        
        // if(gangtype == "wangang") {
        //     if(peng&&wangangs) {
        //         seatData.pengs=peng;
        //         seatData.wangangs=wangangs;
        //     }
        //     // if(seatData.pengs.indexOf(pai) != -1){
        //     //     var idx = seatData.pengs.indexOf(pai);
        //     //     if(idx != -1){
        //     //         seatData.pengs.splice(idx,1);
        //     //     }
        //     // }
        //     // seatData.wangangs.push(pai);      
        // }

        // if(seatData.holds){
        //     for(var i = 0; i <= 4; ++i){
        //         var idx = seatData.holds.indexOf(pai);
        //         if(idx == -1){
        //             //如果没有找到，表示移完了，直接跳出循环
        //             break;
        //         }
        //         seatData.holds.splice(idx,1);
        //     }
        // }
        // if(gangtype == "angang"){
        //     seatData.angangs.push(pai);
        // }
        // else if(gangtype == "diangang"){
        //     seatData.diangangs.push(pai);
        // }
        console.log("data.gangtype="+data.gangtype);
        this.dispatchEvent('gang_notify',{seatData:seatData,gangtype:data.gangtype});
    },
    
    doHu:function(data){
        this.dispatchEvent('hupai',data);
    },
    
    doTurnChange:function(si){
        var data = {
            last:this.turn,//上一次转向
            turn:si,//本次的转向
        }
        this.turn = si;
        this.dispatchEvent('game_chupai',data);
    },

    //是否已经买过or顶过。
    isMaiOrDinged:function(data)
    {
        var str="";
        var arr=this.maiOrDingDiArr;
        for(var j in arr)
        {
            str+=" "+j;
            //如果还有没买的话。
            if(arr[j]==1||arr[j]==3)
            {
                console.log("isMaiOrDinged "+str);
                return;
            }
        }
        console.log("isMaiOrDinged "+str);
        this.dispatchEvent('game_begin');
    },

    getGangs:function() {
        var gangNum =0;
        // console.log('getGangs');
        // console.log(this.seats);
        if(!this.seats) {
            return -1;
        }
        for(var i=0;i<this.seats.length;i++) {
            var seat=this.seats[i];
            // console.log(seat);
            gangNum+=(seat.angangs.length + seat.wangangs.length + seat.diangangs.length);

        }
        console.log("gangNum="+gangNum);
        return gangNum;
    },

    checkYouXianOfHolds:function(youXianArr,holds)
    {
        console.log("checkYouXianOfHolds");
        console.log("holds",holds);
         //check优先牌中，是不是手牌中没有的。
        var youxians=youXianArr;
        var len=youXianArr.length;
        for(var j=0;j<youxians.length;j++)
        {   
            //手牌中，找到优先数组没有的牌。                   
            var idx=holds.indexOf(youxians[j]);
            var pai=youxians[j];
            console.log("idx"+idx+" pai"+pai);
            if(idx==-1)
            {
                console.log("delete pai:"+pai);
                //再在删除数组中，再查找。
                var idx=youXianArr.indexOf(pai);
                youXianArr.splice(idx,1);
            }
        }
    },

    getLen:function(seatData,type)
    {
        // console.log(seatData);
        var length=0;
        var str="length=";
        if(seatData.angangs)
        {
            length+=seatData.angangs.length;
            str+=" angangs"+seatData.angangs.length;
        }else
        {
            console.log("seatData.angangs==null"+seatData.angangs);
        }

        if(seatData.diangangs)
        {
            length+=seatData.diangangs.length;
            str+=" diangangs"+seatData.diangangs.length;
        }else
        {
            console.log("seatData.diangangs==null"+seatData.diangangs);
        }

        if(seatData.wangangs)
        {
            length+=seatData.wangangs.length;
            str+=" wangangs"+seatData.wangangs.length;
        }else
        {
            console.log("seatData.wangangs==null"+seatData.wangangs);
        }

        if(seatData.pengs)
        {
            length+=seatData.pengs.length;
            str+=" pengs"+seatData.pengs.length;
        }else
        {
            console.log("seatData.pengs==null"+seatData.pengs);
        }

        length*=3;

        if(seatData.chis)
        {
            length+=seatData.chis.length;
            str+=" chis"+seatData.chis.length;
        }else
        {
            console.log("seatData.chis==null"+seatData.chis);
        }
        str+=" type="+type;
        console.log(str+" "+length);
        if("other"==type)
        {
            return length;
        }

        var holds = seatData.holds;

        if(holds)
        {
            var str_1=" ";
            var paiNum=0;
            var l = holds.length 
            str_1=" holds.length="+l;
            if( l == 2 || l == 5 || l == 8 || l == 11 || l == 14||l==17){
                paiNum=17;
            }else
            {
                paiNum=16;
            }

            var holdsLen=holds.length;
            str_1+=" "+("length+holdsLen"+length+holdsLen+" paiNum"+paiNum);
            if(length+holdsLen!=paiNum)
            {
                length=paiNum-holdsLen;
            }
        }
        str_1+=" "+("length="+length);
        console.log(str_1);
        return length;

    },
    
    connectGameServer:function(data){
        cc.vv.net.ip = data.ip + ":" + data.port;
        console.log(cc.vv.net.ip);
        var self = this;
        self.isReconncet=false;
        var onConnectOK = function(){
            console.log("onConnectOK");
            cc.vv.net_isConnect=true;
            var sd = {
                token:data.token,
                roomid:data.roomid,
                time:data.time,
                sign:data.sign,
            };
            self.sd=sd;
            if(self.isReconncet) {
                console.log("not send login order");
                // self.isReconncet=false;
                cc.vv.net.send("reconnect_ok",sd);
                return;
            }
            cc.vv.net.send("login",sd);
        };

        //用于断线重连
        var onReConnect=function() {
            console.log("reConnect ok!");
            self.dispatchEvent('reConnect_ok');
            self.isReconncet=true;
        }
        
        var onConnectFailed = function(){
            console.log("failed.");
            cc.vv.wc.hide();
        };
        cc.vv.wc.show("正在进入房间");
        cc.vv.net.connect(onConnectOK,onConnectFailed,onReConnect);
    },

    reConnectGameServer:function() {
        var self=this;

        console.log("reConnectGameServer ");
        // console.log(self.sd);
        var fn=function(data) {
            console.log('testNet ok');
            var onConnectOK=function() {
                cc.vv.net_isConnect=true;
                // console.log('');
                cc.vv.net.send('reconnect_ok',self.sd);
                self.dispatchEvent('reConnect_ok');
            }
            var onConnectFailed = function(){
                console.log("failed.");
                cc.vv.wc.hide();
            };
            var onReConnect=function() {
                console.log("reConnect ok!");
                // self.dispatchEvent('reConnect_ok');
                // self.isReconncet=true;
            }
            // cc.vv.net.close();
            cc.vv.net.connect(onConnectOK,onConnectFailed,onReConnect);
        };
        // var onConnectOK=function() {
        //     cc.vv.net_isConnect=true;
        //     // console.log('');
        //     cc.vv.net.send('reconnect_ok',self.sd);
        //     self.dispatchEvent('reConnect_ok');
        // }
        // var onConnectFailed = function(){
        //     console.log("failed.");
        //     cc.vv.wc.hide();
        // };
        //  var onReConnect=function() {
        //     console.log("reConnect ok!");
        //     // self.dispatchEvent('reConnect_ok');
        //     // self.isReconncet=true;
        // }
        // // cc.vv.net.close();
        // cc.vv.net.connect(onConnectOK,onConnectFailed,onReConnect);
        cc.vv.http.sendRequest("/testNet",{},fn);
    }

});
